package com.iris.live.services.services.impl;

import com.google.common.base.Strings;
import com.iris.live.services.common.DateFormatUtils;
import com.iris.live.services.common.reconsitution.FinanceConstant;
import com.iris.live.services.data.models.销售财务表Model;
import com.iris.live.services.data.models.销售财务账目表Model;
import com.iris.live.services.data.repositories.FinanceReceivablesRepository;
import com.iris.live.services.data.repositories.FinanceWriteOffRepository;
import com.iris.live.services.data.repositories.销售财务表Repository;
import com.iris.live.services.data.repositories.销售财务账目表Repository;
import com.iris.live.services.models.PageData;
import com.iris.live.services.models.RequestBase;
import com.iris.live.services.models.ResultData;
import com.iris.live.services.report.ExcelReportContext;
import com.iris.live.services.report.IExcelReportService;
import com.iris.live.services.report.sources.ExportFinanceWriteOffSource;
import com.iris.live.services.services.FinanceReceivablesService;
import com.iris.live.services.services.FinanceWriteOffService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Map;

/**
 * 财务系统对接模块(核销模块)--业务层
 */
@Service
public class FinanceWriteOffServiceImpl implements FinanceWriteOffService {
    private Logger logger = LoggerFactory.getLogger(ReportServiceImpl.class);

    @Resource
    private FinanceReceivablesRepository financeReceivablesRepository;

    @Resource
    private FinanceWriteOffRepository financeWriteOffRepository;

    @Resource
    private 销售财务表Repository financialRepository;

    @Resource
    private 销售财务账目表Repository financialDetailRepository;

    @Resource
    private FinanceReceivablesService financeReceivablesService;

    @Autowired
    private IExcelReportService excelReportService;

    @Resource(name = "exportFinanceWriteOffSource")
    private ExportFinanceWriteOffSource exportWriteOffSource;

    @Override
    public PageData getWriteOffOrder(String AccountId) {
        List list = financeWriteOffRepository.getWriteOffOrder(AccountId);
        PageData page = new PageData(list,list.size());
        return page;
    }

    @Override
    public PageData getWriteOffDetail(String AccountId, Integer pageSize, Integer pageIndex) {
        return financeWriteOffRepository.getWriteOffDetail(AccountId,pageSize,pageIndex);
    }

    @Override
    public ResultData saveWriteOffAccount(FinanceReceivablesService.ReceivablesAndRefundRequest params) throws Exception {
        ResultData result = new ResultData("false",null,null);

        //做出判空处理
        if (Strings.isNullOrEmpty(params.money)){
            result.setResult("false");
            result.setMessage("请输入收款金额");
            return result;
        }
        if (Strings.isNullOrEmpty(params.billDate)){
            result.setResult("false");
            result.setMessage("请选择收款日期");
            return result;
        }
        if (Strings.isNullOrEmpty(params.payMethod)){
            result.setResult("false");
            result.setMessage("请选择支付方式");
            return result;
        }
        BigDecimal money = new BigDecimal(params.money); // 金额

        // 获取当前账目下的所有核销金额
        String heXiaoMoney = financialDetailRepository.selectWriteMoney(params.AccountId);
        BigDecimal heXiao = new BigDecimal(heXiaoMoney);

        //获取当前账目的挂账金额
        String GuaMoney  = financialDetailRepository.selectGuaMoney(params.AccountId);
        BigDecimal Gua = new BigDecimal(GuaMoney);

        //核销金额不能大于挂账金额
        BigDecimal heji = heXiao.add(money);
        if (heji.compareTo(Gua)==1){
            result.setResult("false");
            result.setMessage("核销金额不能超过挂账金额");
            return result;
        }

        Timestamp time = new Timestamp(System.currentTimeMillis());  // 当前时间
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Timestamp ts = DateFormatUtils.getFormatTimestamp("yyyy-MM-dd HH:mm:ss", new java.util.Date());
        销售财务表Model financialModel = null;


        // 获得单子的订单总价
        BigDecimal totalPrice = financeReceivablesRepository.getOrderTotalPrice(params.quotedNum);
        financialModel = financialRepository.findByOrderNumber(params.initNum);
        if (financialModel != null) {  // 已经有财务主数据,更新金额
            financialModel.set核销金额(financialModel.get核销金额().add(money));
            financialModel.set修改时间(time);
            financialModel.set修改用户(params.user);
            financialModel.set订单总价(totalPrice);
        } else {  // 没有财务主数据,创建数据
            financialModel = new 销售财务表Model();
            financialModel.set许可(params.permit);
            financialModel.set订单编号(params.initNum);
            financialModel.set订单总价(totalPrice);

            financialModel.set核销金额(money);

            //表设计参数不为空， 参数需要初始化
            financialModel.set退款金额(new BigDecimal(0));
            financialModel.set收款金额(new BigDecimal(0));
            financialModel.set挂账金额(new BigDecimal(0));
            financialModel.set开票金额(new BigDecimal(0));
            financialModel.set退票金额(new BigDecimal(0));
            financialModel.set红冲收款金额(new BigDecimal(0));
            financialModel.set红冲退款金额(new BigDecimal(0));
            financialModel.set红冲挂账金额(new BigDecimal(0));
            financialModel.set红冲核销金额(new BigDecimal(0));
            financialModel.set退票金额(new BigDecimal(0));
            financialModel.set退票金额(new BigDecimal(0));

            financialModel.set创建用户(params.user);
            financialModel.set创建时间(time);
            financialModel.set修改用户(params.user);
            financialModel.set修改时间(time);
            financialModel.set删除状态("0");
        }

        financialRepository.save(financialModel);

        // 插入账目明细
        销售财务账目表Model financialDetailModel = new 销售财务账目表Model();
        financialDetailModel.set关联编号(params.AccountId);
        financialDetailModel.set财务编号(financialModel.get财务编号());

        financialDetailModel.set订单编号(params.initNum);
        financialDetailModel.set账目日期(java.sql.Date.valueOf(params.billDate));
        financialDetailModel.set账目类型("核销");
//        financialDetailModel.set挂账类别(params.payMethod);
        financialDetailModel.set支付方式(params.payMethod);
        financialDetailModel.set账目金额(money);
        financialDetailModel.set交易凭证号(params.tradeNO);
        financialDetailModel.set是否红冲("0");
        financialDetailModel.set备注(params.remarks);
        financialDetailModel.set创建用户(params.user);
        financialDetailModel.set创建时间(time);
        financialDetailModel.set修改用户(params.user);
        financialDetailModel.set修改时间(ts);
        financialDetailModel.set删除状态("0");
        financialDetailModel.set账目单号(financeReceivablesService.generateOperationNumber(FinanceConstant.H));
        financialDetailModel.set操作日期(time);

        financialDetailRepository.save(financialDetailModel);

        result.setResult("true");
        result.setMessage("核销保存成功");
        return result;
    }

    @Override
    public PageData getFinanceWriteOff(String permit , FinanceWriteOffService.FinanceWriteOffRequest request) {
        return financeWriteOffRepository.getFinanceWriteOff(permit,request);
    }

    @Override
    public void exportFinanceWriteOff(String permit, HttpServletResponse response,  Map map,RequestBase request) {
        try {
            ExcelReportContext context = new ExcelReportContext();
            String[] columns = map.get("columns").toString().split("[|]");
            map.remove("columns");
            context.setTemplate("templates/财务核销导出模板.xlsx")
                    .setFileName("财务核销导出模板.xlsx")
                    .setSource(exportWriteOffSource)
                    .setStaticSheet(false)
                    .setStartCellIndex(0)
                    .setEndCellIndex(columns.length)
                    .setAutoRowExtended(true)
                    .addParam("permit", permit)
                    .addParam("param", map)
                    .addParam("columns", columns)
                    .addParam("request", request);

            excelReportService.export(context, response.getOutputStream());
        }catch (Exception e){
            logger.error("财务核销导出模板导出异常", e);
        }
    }
}
